from typing import Annotated

from fastapi import APIRouter, Depends, Path, Query

from backend.app.{{ app_name }}.schema.{{ table_name }} import (
    Create{{ schema_name }}Param,
    Delete{{ schema_name }}Param,
    Get{{ schema_name }}Detail,
    Update{{ schema_name }}Param,
)
from backend.app.{{ app_name }}.service.{{ table_name }}_service import {{ table_name }}_service
from backend.common.pagination import DependsPagination, PageData
from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base
from backend.common.security.jwt import DependsJwtAuth
from backend.common.security.permission import RequestPermission
from backend.common.security.rbac import DependsRBAC
from backend.database.db import CurrentSession, CurrentSessionTransaction

router = APIRouter()


@router.get('/{pk}', summary='获取{{ doc_comment }}详情', dependencies=[DependsJwtAuth])
async def get_{{ table_name }}(
    db: CurrentSession, pk: Annotated[int, Path(description='{{ doc_comment }} ID')]
) -> ResponseSchemaModel[Get{{ schema_name }}Detail]:
    {{ table_name }} = await {{ table_name }}_service.get(db=db, pk=pk)
    return response_base.success(data={{ table_name }})


@router.get(
    '',
    summary='分页获取所有{{ doc_comment }}',
    dependencies=[
        DependsJwtAuth,
        DependsPagination,
    ],
)
async def get_{{ table_name }}s_paginated(db: CurrentSession) -> ResponseSchemaModel[PageData[Get{{ schema_name }}Detail]]:
    page_data = await {{ table_name }}_service.get_list(db=db)
    return response_base.success(data=page_data)


@router.post(
    '',
    summary='创建{{ doc_comment }}',
    dependencies=[
        Depends(RequestPermission('{{ permission }}:add')),
        DependsRBAC,
    ],
)
async def create_{{ table_name }}(db: CurrentSessionTransaction, obj: Create{{ schema_name }}Param) -> ResponseModel:
    await {{ table_name }}_service.create(db=db, obj=obj)
    return response_base.success()


@router.put(
    '/{pk}',
    summary='更新{{ doc_comment }}',
    dependencies=[
        Depends(RequestPermission('{{ permission }}:edit')),
        DependsRBAC,
    ],
)
async def update_{{ table_name }}(
    db: CurrentSessionTransaction, pk: Annotated[int, Path(description='{{ doc_comment }} ID')], obj: Update{{ schema_name }}Param
) -> ResponseModel:
    count = await {{ table_name }}_service.update(db=db, pk=pk, obj=obj)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.delete(
    '',
    summary='批量删除{{ doc_comment }}',
    dependencies=[
        Depends(RequestPermission('{{ permission }}:del')),
        DependsRBAC,
    ],
)
async def delete_{{ table_name }}s(db: CurrentSessionTransaction, obj: Delete{{ schema_name }}Param) -> ResponseModel:
    count = await {{ table_name }}_service.delete(db=db, obj=obj)
    if count > 0:
        return response_base.success()
    return response_base.fail()
